package cn.lingyangwl.agile.msg.push.core.sender;

import cn.lingyangwl.agile.msg.push.api.constatnts.*;
import cn.lingyangwl.agile.msg.push.api.model.content.*;
import cn.lingyangwl.agile.msg.push.core.*;
import cn.lingyangwl.agile.msg.push.core.channel.*;
import cn.lingyangwl.agile.msg.push.core.channel.client.*;
import cn.lingyangwl.framework.tool.core.exception.*;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.config.WxMpConfigStorage;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 微信消息推送
 * @author shenguangyang
 */
@Slf4j
@Component
public class WxMpSender implements MsgSender {
    @Resource
    private ChannelClientManager channelClientManager;

    @Override
    public void sendMessage(PushTaskContext context) {
        MsgSettings msgSettings = context.getMsgSettings();

        context.setChannelCode(ChannelCodeEnum.WX_MP);
        MsgParam msgParam = context.getMsgParam();
        WxMpMsgClient wxMpMsgClient = (WxMpMsgClient) channelClientManager.getChannelClient(context.getChannelType());
        context.setChannelCode(wxMpMsgClient.channelCode());

        WxMpService wxMpService = wxMpMsgClient.getWxMpService();
        WxMpConfigStorage wxMpConfigStorage = wxMpMsgClient.getWxMpConfigStorage();

        log.info("accessToken: {}", wxMpConfigStorage.getAccessToken());
        try {
            // 创建模板消息，设置模板id、指定模板消息要发送的目标用户
            WxMpTemplateMessage wxMpTemplateMessage = WxMpTemplateMessage.builder()
                    .templateId(msgSettings.getTemplateId())
                    .toUser(msgParam.getToUser())
                    .url(msgParam.getPageUrl())
                    .build();

            // 填充模板消息中的变量
            for (TplField tpl : msgSettings.getTplField().values()) {
                wxMpTemplateMessage.addData(new WxMpTemplateData(tpl.getKey(), String.valueOf(tpl.getValue()), tpl.getColor()));
            }

            // 发送模板消息，返回消息id
            String msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(wxMpTemplateMessage);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("msgId", msgId);
            context.setPushResult(jsonObject.toJSONString());
        } catch (Exception e) {
            context.setPushStatus(MsgPushStatus.FAIL);
            context.setPushResult(e.getMessage());
            throw new BizException(-1, e.getMessage());
        }
    }

    @Override
    public ChannelTypeEnum channelType() {
        return ChannelTypeEnum.WX_MP;
    }
}
